package org.bouncycastle.asn1.x9;

import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;

import java.math.BigInteger;

/**
 * X9整数类型转换，用于椭圆曲线算法
 * 
 * @author john.peng
 *
 */
public class X9IntegerConverter {
	/**
	 * 获取椭圆曲线字节长度
	 * 
	 * @param c 椭圆曲线
	 * @return 字节长度
	 */
	public int getByteLength(ECCurve c) {
		return (c.getFieldSize() + 7) / 8;
	}

	/**
	 * 获取椭圆字段字节长度
	 * 
	 * @param fe 椭圆字段元素
	 * @return 字节长度
	 */
	public int getByteLength(ECFieldElement fe) {
		return (fe.getFieldSize() + 7) / 8;
	}

	/**
	 * 将一个BigInteger转换为字节数组
	 * 
	 * @param s       BigInteger数据
	 * @param qLength 长度
	 * @return 字节数组
	 */
	public byte[] integerToBytes(BigInteger s, int qLength) {
		byte[] bytes = s.toByteArray();

		if (qLength < bytes.length) {
			byte[] tmp = new byte[qLength];

			System.arraycopy(bytes, bytes.length - tmp.length, tmp, 0, tmp.length);

			return tmp;
		} else if (qLength > bytes.length) {
			byte[] tmp = new byte[qLength];

			System.arraycopy(bytes, 0, tmp, tmp.length - bytes.length, bytes.length);

			return tmp;
		}

		return bytes;
	}
}
